
import mainDb from "../dbs/main.db";
import { http } from 'system';

/**
 * 获取抓取源列表
 * @param {string} siteTitle - 站点标题筛选（可选）
 * @param {boolean} isEnable - 是否启用筛选（可选）
 * @param {number} page - 页码（默认1）
 * @param {number} pageSize - 每页数量（默认10）
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { list:[{id:number, site_url:string, site_title:string, is_enable:boolean, enhanced_crawl_flag:boolean, last_crawl_time:string, article_count:number}],total:number,page:number, pageSize:number }}
 */
async function getSourceList(siteTitle = '', isEnable = null, page = 1, pageSize = 10) {
    try {
        const queryParams = {
            "total@": "crawl_sources[]/total",
            "crawl_sources[]": {
                page,
                count: pageSize,
                query: 2,
                "@order": "modify_at-",
                "@column": "id,site_url,site_title,is_enable,enhanced_crawl_flag,last_crawl_time"
            }
        };

        // 添加搜索条件
        if (siteTitle) {
            queryParams["crawl_sources[]"]["site_title$"] = '%' + siteTitle + '%';
        }

        if (isEnable !== null) {
            queryParams["crawl_sources[]"]["is_enable"] = isEnable ? 1 : 0;
        }

        const result = await mainDb.queryAsync(queryParams);
        
        // 获取每个源的文章数量
        const sourceList = result.crawl_sources || [];
        for (let i = 0; i < sourceList.length; i++) {
            const source = sourceList[i];
            const countResult = await mainDb.queryAsync({
                "crawl_site_content": {
                    source_id: source.id,
                    "@column": "COUNT(id) as count"
                }
            });
            source.article_count = countResult.crawl_site_content ? countResult.crawl_site_content.count || 0 : 0;
        }

        return {
            code: 200,
            message: '',
            data: {
                list: sourceList,
                total: result.total || 0,
                page,
                pageSize
            }
        };
    } catch (error) {
        console.error('获取抓取源列表失败:', error);
        return {
            code: 500,
            message: '获取抓取源列表失败',
            data: error.message
        };
    }
}

/**
 * 添加抓取源
 * @param {string} siteUrl - 站点URL
 * @param {string} siteTitle - 站点标题
 * @param {boolean} isEnable - 是否启用（默认true）
 * @param {boolean} enhancedCrawlFlag - 是否启用增强抓取（默认false）
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { id:number }}
 */
async function addSource(siteUrl, siteTitle, isEnable = true, enhancedCrawlFlag = false) {
    try {
        if (!siteUrl || !siteTitle) {
            return {
                code: 400,
                message: '站点URL和标题不能为空',
                data: null
            };
        }

        // 检查URL是否已存在
        const existCheck = await mainDb.queryAsync({
            "crawl_sources": {
                site_url: siteUrl
            }
        });

        if (existCheck.crawl_sources && existCheck.crawl_sources.id) {
            return {
                code: 400,
                message: '该站点URL已存在',
                data: null
            };
        }

        // 确保 isEnable 是布尔值
        const isEnabled = typeof isEnable === 'boolean' ? isEnable : (isEnable === 'true' || isEnable === '1' || isEnable === 1);
        
        // 确保 enhancedCrawlFlag 是布尔值
        const isEnhancedCrawl = typeof enhancedCrawlFlag === 'boolean' ? enhancedCrawlFlag : (enhancedCrawlFlag === 'true' || enhancedCrawlFlag === '1' || enhancedCrawlFlag === 1);

        // 生成兼容的日期时间格式 (YYYY-MM-DD HH:mm:ss)
        const now = new Date();
        const formattedDate = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

        const id = await mainDb.addAsync({
            "crawl_sources": {
                site_url: siteUrl,
                site_title: siteTitle,
                is_enable: isEnabled ? 1 : 0,
                enhanced_crawl_flag: isEnhancedCrawl ? 1 : 0,
                modify_at: formattedDate
            }
        });

        return {
            code: 200,
            message: '添加抓取源成功',
            data: { id }
        };
    } catch (error) {
        console.error('添加抓取源失败:', error);
        return {
            code: 500,
            message: '添加抓取源失败',
            data: error.message
        };
    }
}

/**
 * 更新抓取源
 * @param {number} id - 抓取源ID
 * @param {string} siteUrl - 站点URL
 * @param {string} siteTitle - 站点标题
 * @param {boolean} isEnable - 是否启用
 * @param {boolean} enhancedCrawlFlag - 是否启用增强抓取
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null }
 */
async function updateSource(id, siteUrl, siteTitle, isEnable, enhancedCrawlFlag) {
    try {
        if (!id || !siteUrl || !siteTitle) {
            return {
                code: 400,
                message: '抓取源ID、站点URL和标题不能为空',
                data: null
            };
        }

        // 检查抓取源是否存在
        const existCheck = await mainDb.queryAsync({
            "crawl_sources": {
                id: id
            }
        });

        if (!existCheck.crawl_sources || !existCheck.crawl_sources.id) {
            return {
                code: 404,
                message: '抓取源不存在',
                data: null
            };
        }

        // 检查URL是否已被其他抓取源使用
        const urlCheck = await mainDb.queryAsync({
            "crawl_sources": {
                site_url: siteUrl,
                "id!": id
            }
        });

        if (urlCheck.crawl_sources && urlCheck.crawl_sources.id) {
            return {
                code: 400,
                message: '该站点URL已被其他抓取源使用',
                data: null
            };
        }

        // 确保 isEnable 是布尔值
        const isEnabled = typeof isEnable === 'boolean' ? isEnable : (isEnable === 'true' || isEnable === '1' || isEnable === 1);
        
        // 确保 enhancedCrawlFlag 是布尔值
        const isEnhancedCrawl = typeof enhancedCrawlFlag === 'boolean' ? enhancedCrawlFlag : (enhancedCrawlFlag === 'true' || enhancedCrawlFlag === '1' || enhancedCrawlFlag === 1);

        // 生成兼容的日期时间格式 (YYYY-MM-DD HH:mm:ss)
        const now = new Date();
        const formattedDate = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

        await mainDb.modifyAsync({
            "crawl_sources": {
                id: id,
                site_url: siteUrl,
                site_title: siteTitle,
                is_enable: isEnabled ? 1 : 0,
                enhanced_crawl_flag: isEnhancedCrawl ? 1 : 0,
                modify_at: formattedDate
            }
        });

        return {
            code: 200,
            message: '更新抓取源成功',
            data: null
        };
    } catch (error) {
        console.error('更新抓取源失败:', error);
        return {
            code: 500,
            message: '更新抓取源失败',
            data: error.message
        };
    }
}

/**
 * 删除抓取源
 * @param {number} id - 抓取源ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null }
 */
async function deleteSource(id) {
    try {
        if (!id) {
            return {
                code: 400,
                message: '抓取源ID不能为空',
                data: null
            };
        }

        // 检查抓取源是否存在
        const existCheck = await mainDb.queryAsync({
            "crawl_sources": {
                id: id
            }
        });

        if (!existCheck.crawl_sources || !existCheck.crawl_sources.id) {
            return {
                code: 404,
                message: '抓取源不存在',
                data: null
            };
        }

        await mainDb.removeAsync({
            "crawl_sources": {
                id: id
            }
        });

        return {
            code: 200,
            message: '删除抓取源成功',
            data: null
        };
    } catch (error) {
        console.error('删除抓取源失败:', error);
        return {
            code: 500,
            message: '删除抓取源失败',
            data: error.message
        };
    }
}

/**
 * 获取抓取源详情
 * @param {number} id - 抓取源ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { id:number, site_url:string, site_title:string, is_enable:boolean, enhanced_crawl_flag:boolean, create_at:string, modify_at:string, last_crawl_time:string }}
 */
async function getSourceDetail(id) {
    try {
        if (!id) {
            return {
                code: 400,
                message: '抓取源ID不能为空',
                data: null
            };
        }

        const result = await mainDb.queryAsync({
            "crawl_sources": {
                id: id
            }
        });

        if (!result.crawl_sources || !result.crawl_sources.id) {
            return {
                code: 404,
                message: '抓取源不存在',
                data: null
            };
        }

        return {
            code: 200,
            message: '',
            data: result.crawl_sources
        };
    } catch (error) {
        console.error('获取抓取源详情失败:', error);
        return {
            code: 500,
            message: '获取抓取源详情失败',
            data: error.message
        };
    }
}

/**
 * 启用/禁用抓取源
 * @param {number} id - 抓取源ID
 * @param {boolean} enable - 是否启用
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null }
 */
async function toggleSourceStatus(id, enable) {
    try {
        if (!id) {
            return {
                code: 400,
                message: '抓取源ID不能为空',
                data: null
            };
        }

        // 检查抓取源是否存在
        const existCheck = await mainDb.queryAsync({
            "crawl_sources": {
                id: id
            }
        });

        if (!existCheck.crawl_sources || !existCheck.crawl_sources.id) {
            return {
                code: 404,
                message: '抓取源不存在',
                data: null
            };
        }

        // 确保 enable 是布尔值
        const isEnabled = typeof enable === 'boolean' ? enable : (enable === 'true' || enable === '1' || enable === 1);

        // 生成兼容的日期时间格式 (YYYY-MM-DD HH:mm:ss)
        const now = new Date();
        const formattedDate = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

        await mainDb.modifyAsync({
            "crawl_sources": {
                id: id,
                is_enable: isEnabled ? 1 : 0,
                modify_at: formattedDate
            }
        });

        return {
            code: 200,
            message: isEnabled ? '启用抓取源成功' : '禁用抓取源成功',
            data: null
        };
    } catch (error) {
        console.error('切换抓取源状态失败:', error);
        return {
            code: 500,
            message: '切换抓取源状态失败',
            data: error.message
        };
    }
}

/**
 * 切换增强抓取标记
 * @param {number} id - 抓取源ID
 * @param {boolean} enhancedCrawlFlag - 是否启用增强抓取
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null }
 */
async function toggleEnhancedCrawlFlag(id, enhancedCrawlFlag) {
    try {
        if (!id) {
            return {
                code: 400,
                message: '抓取源ID不能为空',
                data: null
            };
        }

        // 检查抓取源是否存在
        const existCheck = await mainDb.queryAsync({
            "crawl_sources": {
                id: id
            }
        });

        if (!existCheck.crawl_sources || !existCheck.crawl_sources.id) {
            return {
                code: 404,
                message: '抓取源不存在',
                data: null
            };
        }

        // 确保 enhancedCrawlFlag 是布尔值
        const isEnhancedCrawl = typeof enhancedCrawlFlag === 'boolean' ? enhancedCrawlFlag : (enhancedCrawlFlag === 'true' || enhancedCrawlFlag === '1' || enhancedCrawlFlag === 1);

        // 生成兼容的日期时间格式 (YYYY-MM-DD HH:mm:ss)
        const now = new Date();
        const formattedDate = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

        await mainDb.modifyAsync({
            "crawl_sources": {
                id: id,
                enhanced_crawl_flag: isEnhancedCrawl ? 1 : 0,
                modify_at: formattedDate
            }
        });

        return {
            code: 200,
            message: isEnhancedCrawl ? '启用增强抓取成功' : '禁用增强抓取??功',
            data: null
        };
    } catch (error) {
        console.error('切换增强抓取标记失败:', error);
        return {
            code: 500,
            message: '切换增强抓取标记失败',
            data: error.message
        };
    }
}

/**
 * 获取抓取源注释列表
 * @param {number} sourceId - 抓取源ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { list:[{id:number, target_type:string, target_id:number, content:string, user_id:number, create_at:string, modify_at:string}] }}
 */
async function getSourceComments(sourceId) {
    try {
        if (!sourceId) {
            return {
                code: 400,
                message: '抓取源ID不能为空',
                data: null
            };
        }

        const result = await mainDb.queryAsync({
            "comments[]": {
                target_type: 'source',
                target_id: sourceId,
                "@order": "modify_at-"
            }
        });

        return {
            code: 200,
            message: '',
            data: {
                list: result.comments || []
            }
        };
    } catch (error) {
        console.error('获取抓取源注释列表失败:', error);
        return {
            code: 500,
            message: '获取抓取源注释列表失败',
            data: error.message
        };
    }
}

/**
 * 添加抓取源注释
 * @param {number} sourceId - 抓取源ID
 * @param {string} content - 注释内容
 * @param {number} userId - 用户ID（可选）
 * @returns {Object} 标准响应格式 {code:number, message:string, data: { id:number }}
 */
async function addSourceComment(sourceId, content, userId = null) {
    try {
        if (!sourceId || !content) {
            return {
                code: 400,
                message: '抓取源ID和注释内容不能为空',
                data: null
            };
        }

        // 检查抓取源是否存在
        const sourceCheck = await mainDb.queryAsync({
            "crawl_sources": {
                id: sourceId
            }
        });

        if (!sourceCheck.crawl_sources || !sourceCheck.crawl_sources.id) {
            return {
                code: 404,
                message: '抓取源不存在',
                data: null
            };
        }

        // 生成兼容的日期时间格式 (YYYY-MM-DD HH:mm:ss)
        const now = new Date();
        const formattedDate = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

        const id = await mainDb.addAsync({
            "comments": {
                target_type: 'source',
                target_id: sourceId,
                content: content,
                user_id: userId,
                create_at: formattedDate,
                modify_at: formattedDate
            }
        });

        return {
            code: 200,
            message: '添加抓取源注释成功',
            data: { id }
        };
    } catch (error) {
        console.error('添加抓取源注释失败:', error);
        return {
            code: 500,
            message: '添加抓取源注释失败',
            data: error.message
        };
    }
}

/**
 * 更新抓取源注释
 * @param {number} commentId - 注释ID
 * @param {string} content - 注释内容
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null }
 */
async function updateSourceComment(commentId, content) {
    try {
        if (!commentId || !content) {
            return {
                code: 400,
                message: '注释ID和注释内容不能为空',
                data: null
            };
        }

        // 检查注释是否存在
        const commentCheck = await mainDb.queryAsync({
            "comments": {
                id: commentId,
                target_type: 'source'
            }
        });

        if (!commentCheck.comments || !commentCheck.comments.id) {
            return {
                code: 404,
                message: '注释不存在',
                data: null
            };
        }

        // 生成兼容的日期时间格式 (YYYY-MM-DD HH:mm:ss)
        const now = new Date();
        const formattedDate = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');

        await mainDb.modifyAsync({
            "comments": {
                id: commentId,
                content: content,
                modify_at: formattedDate
            }
        });

        return {
            code: 200,
            message: '更新抓取源注释成功',
            data: null
        };
    } catch (error) {
        console.error('更新抓取源注释失败:', error);
        return {
            code: 500,
            message: '更新抓取源注释失败',
            data: error.message
        };
    }
}

/**
 * 删除抓取源注释
 * @param {number} commentId - 注释ID
 * @returns {Object} 标准响应格式 {code:number, message:string, data: null }
 */
async function deleteSourceComment(commentId) {
    try {
        if (!commentId) {
            return {
                code: 400,
                message: '注释ID不能为空',
                data: null
            };
        }

        // 检查注释是否存在
        const commentCheck = await mainDb.queryAsync({
            "comments": {
                id: commentId,
                target_type: 'source'
            }
        });

        if (!commentCheck.comments || !commentCheck.comments.id) {
            return {
                code: 404,
                message: '注释不存在',
                data: null
            };
        }

        await mainDb.removeAsync({
            "comments": {
                id: commentId
            }
        });

        return {
            code: 200,
            message: '删除抓取源注释成功',
            data: null
        };
    } catch (error) {
        console.error('删除抓取源注释失败:', error);
        return {
            code: 500,
            message: '删除抓取源注释失败',
            data: error.message
        };
    }
}

// 导出所有方法
export { 
    getSourceList, 
    addSource, 
    updateSource, 
    deleteSource, 
    getSourceDetail, 
    toggleSourceStatus,
    toggleEnhancedCrawlFlag,
    getSourceComments,
    addSourceComment,
    updateSourceComment,
    deleteSourceComment
};